import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Input,
  Button,
  Divider,
  Drawer,
  Select,
  Modal,
  Dropdown,
  Icon,
  Menu,
} from 'antd';
import { connect } from 'dva';
import { useAntdTable } from '@umijs/hooks';
import SlickTable from '@/components/SlickTable';
import { getPageSizeByCardHeight } from '@/utils/utils';
import request from '@/utils/request';
import Operpage from './components/Operpage';
import NumManage from './components/NumManage';

const { Option } = Select;

// const namespace = 'NumpoolManage';

function NumpoolManage({ size: { height }, form }) {
  const { getFieldDecorator } = form;

  const [size, setSize] = useState(getPageSizeByCardHeight(height - 32 - 8));
  const [paramsObj, setParamsObj] = useState({});
  // 右抽屉显示隐藏控制
  const [visible, setVisible] = useState(false);
  // 状态 add 、 detail 、 edit
  const [status, setStatus] = useState('');
  // 工号管理模态框的显示隐藏控制
  const [numVisible, setNumVisible] = useState(false);

  const getTableData = ({ current, pageSize, paramsObj }) => {
    return request('oc/StaffPoolManagerController/findStaffPools.do', {
      data: {
        pageNum: current,
        pageSize: pageSize,
        sortName: '',
        sortOrder: 'asc',
        ...paramsObj,
      },
    }).then(res => {
      if (Array.isArray(res.list)) {
        return {
          total: res.total,
          data: res.list.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTableData({ ...params, pageSize: size, paramsObj });
    },
    [paramsObj, height],
    {
      defaultPageSize: size,
      form,
    }
  );
  const { pagination, ...restTableProps } = tableProps;

  useEffect(() => {
    setSize(getPageSizeByCardHeight(height - 32 - 8));
  }, [height]);

  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // console.log(fieldsValue);
      setParamsObj({
        ...fieldsValue,
      });
    });
  };

  const handleOper = (status, record) => {
    setStatus(status);
    setVisible(true);
    // savePassData(record);
  };

  const onClose = () => {
    setVisible(false);
  };

  const handleReset = () => {
    form.resetFields();
  };

  const numClose = () => {
    setNumVisible(false);
  };

  const columns = [
    {
      title: '号池名称',
      dataIndex: 'poolName',
      ellipsis: true,
      render: (text, record) => {
        return (
          <a
            onClick={() => {
              handleOper('detail', record);
            }}
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '预占时间（分）',
      dataIndex: 'preholdingTime',
      ellipsis: true,
    },
    {
      title: '每次分配最大数量',
      dataIndex: 'allocationNum',
      ellipsis: true,
    },
    {
      title: '分配间隔时间',
      dataIndex: 'intervalTime',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      align: 'center',
      ellipsis: true,
      render: (text, record) => {
        return text === '1000' ? (
          <span className="text-color">启用</span>
        ) : (
          <span className="text-danger">停用</span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                setNumVisible(true);
              }}
            >
              工号管理
            </a>
            <Divider type="vertical" />
            <Dropdown
              placement="bottomCenter"
              overlay={
                <Menu>
                  <Menu.Item>
                    <a
                      onClick={() => {
                        handleOper('edit', record);
                      }}
                    >
                      修改
                    </a>
                  </Menu.Item>
                  <Menu.Item>
                    <a
                      onClick={() => {
                        Modal.confirm({
                          content: '确认是否停用当前号池配置?',
                          okText: '停用',
                          okType: 'danger',
                          cancelText: '取消',
                        });
                      }}
                    >
                      停用
                    </a>
                  </Menu.Item>
                  <Menu.Item>
                    <a
                      onClick={() => {
                        Modal.confirm({
                          content: '确认是否删除当前号池配置?',
                          okText: '删除',
                          okType: 'danger',
                          cancelText: '取消',
                        });
                      }}
                    >
                      删除
                    </a>
                  </Menu.Item>
                </Menu>
              }
            >
              <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                更多操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        );
      },
    },
  ];

  return (
    <>
      <Card
        title="工号池管理列表"
        style={{ minHeight: height }}
        className="cute"
        extra={
          <Button
            type="primary"
            onClick={() => {
              handleOper('add');
            }}
          >
            新增号池
          </Button>
        }
      >
        <Form className="flow fix-label padding-bottom">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="号池名称">
                {getFieldDecorator('systemSource', {
                  // initialValue: '11',
                })(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="成员工号">
                {getFieldDecorator('queryType', {
                  // initialValue: '11',
                })(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="状态">
                {getFieldDecorator('exceptionCode')(
                  <Select placeholder="请选择">
                    <Option value="1000">启用</Option>
                    <Option value="1100">停用</Option>
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6} className="text-right">
              <Button type="primary" onClick={submit}>
                查询
              </Button>
              <Button className="margin-left" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <SlickTable
          style={{ marginTop: 8 }}
          rowKey={record => record.exeptionId}
          columns={columns}
          {...restTableProps}
          data={{
            pagination: {
              ...pagination,
              pageSize: size,
            },
          }}
        />
      </Card>
      <Drawer
        title={
          status === 'add'
            ? '新增工号池信息'
            : status === 'edit'
            ? '修改工号池信息'
            : '工号池信息详情'
        }
        destroyOnClose
        width={680}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Operpage
          close={onClose}
          refresh={refresh}
          disabled={status === 'detail' ? true : false}
          status={status}
        />
      </Drawer>
      {numVisible ? <NumManage visiable={numVisible} close={numClose} /> : null}
    </>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(NumpoolManage));
